package seehope.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectionDemo03 {
    public static void main(String[] args) throws Exception{
        Class<?> class1 = Class.forName("seehope.reflect.Person");
        Constructor constructor = class1.getConstructor(String.class, int.class);
//        Person person = (Person) class1.newInstance("张三", 19);
        Person person = new Person("张三", 20);
        System.out.println("---------遍历所有Public修饰的属性---------");
        Field[] publicFields = class1.getFields();
        for(Field publicField : publicFields){
            System.out.println("成员变量名称:" + publicField.getName());
            System.out.println("成员变量类型:" + publicField.getType());

            if(publicField.getType().equals(String.class)){
                System.out.println("成员变量的值:" + publicField.get(person));
            } else if (publicField.getType().equals(int.class)){
                System.out.println("成员变量的值:" + publicField.getInt(person));
            }
            System.out.println("");
        }

        System.out.println("---------遍历所有属性---------");
        Field[] fields = class1.getDeclaredFields();
        for(Field field : fields){
            System.out.println("成员变量名称:" + field.getName());
            System.out.println("成员变量类型:" + field.getType());
            System.out.println("成员变量修饰:" + (field.getModifiers() == 1 ? "public" : "private"));

            if(field.getType().equals(String.class)){
                System.out.println("成员变量的值:" + field.get(person));
            } else if(field.getType().equals(int.class)){
                if(field.getModifiers() == Modifier.PRIVATE) {
                    field.setAccessible(true);
                }
                System.out.println("成员变量的值:" + field.getInt(person));
            }
            System.out.println("");
        }

        System.out.println("---------访问特定的成员变量---------");
        Field fName = class1.getField("name");
        fName.set(person, "李四");
        System.out.println(person);
        Field fAge = class1.getDeclaredField("age");
        fAge.setAccessible(true);
        fAge.set(person, 18);
        System.out.println(person);
    }
}
